package com.miyu.client1.controller.bookMagic;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.miyu.client1.service.magic.BookMagicService;
import com.miyu.client1.utils.redis.redisUtils.util.RedisValUtil;
import org.apache.commons.lang.StringEscapeUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/bookMagic")
public class bookMagic {


    @Autowired
    private BookMagicService bs;


    /**
     * 根据配置规则搜索数据
     * @param param
     * @return
     */
    @RequestMapping("/searchBook")
    public JSONObject searchBook(@RequestBody JSONObject param){
        JSONArray rs = new JSONArray();
        rs =  bs.searchBook(param);
        JSONObject ts = new JSONObject();

        ts.put("data", rs);
        ts.put("code","0");
        ts.put("count",rs.size());
        ts.put("msg","数据返回成功");

        return ts;
    }

    /**
     * 获取数据章节+数据详情
     * @param param
     * @return
     */
    @RequestMapping("/queryDetailBookList")
    public JSONObject queryDetailBookList(@RequestBody JSONObject param){
      //  String bookId = param.getString("bookId");
        JSONObject rs = bs.queryDetailBookList(param);
        JSONObject ts = new JSONObject();

        ts.put("data",rs);
        ts.put("code","0");
        ts.put("count",rs.getJSONArray("zjList").size());
        ts.put("msg","接收数据成功");
        return ts;
    }

    /**
     * 阅读章节
     * @param param
     * @return
     */
    @RequestMapping("/readMagicBook")
    public JSONObject queryReadBook(@RequestBody JSONObject param){
        JSONObject rs =  bs.queryReadBook(param);

        JSONObject ts = new JSONObject();
        return rs;
    }

    /**
     * 小说下载
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/downloadBook")
    public HttpServletResponse downloadBook(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String param = StringEscapeUtils.unescapeJavaScript(request.getParameter("content").trim());
        System.out.println(param);
        JSONObject jsonObject = JSONObject.parseObject(StringEscapeUtils.unescapeJavaScript(param));
        System.out.println("进入下载方法"+jsonObject);
        String path = bs.downloadBook(param);

        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));

            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"),"ISO8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
            int count =0;
            byte[] by = new byte[1024];
            //通过response对象获取OutputStream流
            OutputStream out=  response.getOutputStream();

            while((count=fis.read(by))!=-1){
                out.write(by, 0, count);//将缓冲区的数据输出到浏览器
            }
            fis.close();
            out.flush();
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    @RequestMapping("/queryBookList")
    public JSONArray queryBookList(@RequestBody JSONObject param){
        JSONArray rs = bs.queryBookList(param);
        JSONObject ts = new JSONObject();
        ts.put("data",rs);
        ts.put("code","0");
        ts.put("count",rs.size());
        ts.put("msg","接收数据成功");
        return  rs;
    }

    @RequestMapping("/initData")
    public JSONObject initData() throws Exception{
        return bs.initData();
    }
    @Autowired
    private RedisValUtil redisValUtil;

    @RequestMapping("/updateChapter")
    public JSONObject updateChapter(@RequestBody  JSONObject jo ){

        redisValUtil.set(2,"ceshi","测试redis是否启用");
        System.out.println(redisValUtil.get(2,"ceshi"));
        return bs.updateChapter(jo);
 /*       JSONObject ts = new JSONObject();
        ts.put("data","rs");
        ts.put("code","0");

        ts.put("msg","接收数据成功");

        return ts;*/
    }
    /**
     * 优化规则解析 统一处理解析数据 根据不同的类型 进入解析不同的规则内
     *
     * @return
     */
    @RequestMapping("SearchPage")
    public JSONArray SearchPage(@RequestBody JSONObject param){

        return  bs.SearchPage(param);
    }
    /**
     * 书籍明细页面
     */
    @RequestMapping("getBookInfo")
    public JSONObject getBookInfo(@RequestBody JSONObject param){
        return bs.getBookInfo(param);
    }


    @RequestMapping("readBook")
    public JSONObject readBook(@RequestBody JSONObject param){
        return  bs.readBook(param);
    }


    @RequestMapping("downloadFile")
    public HttpServletResponse downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String param = StringEscapeUtils.unescapeJavaScript(request.getParameter("content").trim());
        JSONObject para = JSONObject.parseObject(param);
        JSONObject jsonObject = JSONObject.parseObject(StringEscapeUtils.unescapeJavaScript(param));
        //有具体下载链接接入原网站下载
        if(para.containsKey("bookDown")){
            String url = para.getString("bookDown");
            String bookName = url.substring(url.lastIndexOf("/")+1,url.lastIndexOf("."))+url.substring(url.lastIndexOf("."));
            url=new String(url.getBytes("utf-8"),"utf-8");
            Connection.Response execute = null;
            execute = Jsoup.connect(url).timeout(100000).maxBodySize(0).ignoreContentType(true).execute();
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(bookName.getBytes("utf-8"),"ISO8859-1"));
            response.setContentType("application/octet-stream");
            OutputStream out=  response.getOutputStream();
            out.write(execute.bodyAsBytes());
            out.close();
            return null;
        }


        String path = bs.downloadFile(para); //生成临时文件以供下载
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));

            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"),"ISO8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
            int count =0;
            byte[] by = new byte[1024];
            //通过response对象获取OutputStream流
            OutputStream out=  response.getOutputStream();

            while((count=fis.read(by))!=-1){
                out.write(by, 0, count);//将缓冲区的数据输出到浏览器
            }
            fis.close();
            out.flush();
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }


}
